<?php
namespace Swiftx\Component\Xml;

use Whoops\Exception\ErrorException;

class Node {

    /**
     * 节点对象
     * @var \SimpleXMLElement
     */
    protected $simpleXMLElement;

    /**
     * 获取子元素
     * @var null|Node[]
     */
    protected $children = null;

    /**
     * 元素属性集合
     * @var Attribute[]
     */
    protected $attributes = null;

    /**
     * 创建节点元素
     * @param \SimpleXMLElement $element
     */
    public function __construct(\SimpleXMLElement $element=null){
        $this->simpleXMLElement = $element;
    }

    /**
     * 获取标签名
     * @return string
     */
    public function getName():string {
        return $this->simpleXMLElement->getName();
    }

    /**
     * 根据节点名称获取元素
     * @param string|null $name
     * @return Node[]
     */
    public function children(string $name=null):array {
        if($this->children === null){
            $this->children = [];
            /** @var \SimpleXMLElement $child */
            foreach ($this->simpleXMLElement->children() as $child)
                $this->children[] = new Node($child);
        }
        if($name === null) return $this->children;
        $result = [];
        foreach ($this->children as $node){
            if($node->getName() == $name)
                $result[] = $node;
        }
        return $result;
    }

    /**
     * 获取元素属性集合
     * @return Attribute[]
     */
    public function getAttributes():array {
        if($this->attributes === null){
            $this->attributes = [];
            /** @var \SimpleXMLElement $child */
            foreach ($this->simpleXMLElement->attributes() as $child)
                $this->attributes[] = $attr = new Attribute($child);
        }
        return $this->attributes;
    }

    /**
     * 判断属性存在
     * @return bool
     */
    public function hasAttribute(string $name):bool {
        foreach ($this->getAttributes() as $attribute)
            if($attribute->getName() == $name) return true;
        return false;
    }

    /**
     * 获取元素属性
     * @return Attribute
     */
    public function getAttribute(string $name):Attribute {
        foreach ($this->getAttributes() as $attribute)
            if($attribute->getName() == $name) return $attribute;
        return null;
    }

    /**
     * 转换成字符串
     * @return string
     */
    public function __toString(){
        return (string)$this->simpleXMLElement;
    }

}